const log4js      = require('../../utils/logUtils');
const logger      = log4js.getLogger('web');
const constants   = require('../../db/constants');
const proxyModel = require('../../model/proxy');
const basectrl = require("./basectrl");
const deviceCache = require("../../db/deviceCache");
const sipUtils = require("../../utils/sipUtils");
const modelChannel = require("../../model/channel");
const zlMediaKit = require("../../service/ZlMediaKitUtils");
const mediaServerModel = require("../../model/mediaServer");
/**
 * 拉流代理
 */
const TAG = "[拉流代理]";
let Proxy = {
    add: async function (req, res) {
        if(!basectrl.hasLogin(req, res)){
            return;
        }
        // 如果 channel_id 或 name已经存在，则不允许添加
        let existChannelId = await proxyModel.exist('channel_id', req.body.channel_id, null);
        // let existName = await proxyModel.exist('name', req.body.name, null);
        if (existChannelId ) {
            logger.info(TAG, "新增时发现重复的channel_id或name");
            let ret = Object.assign(constants.httpCode.DUPLICATED);
            res.send(ret);
            return;
        }
        logger.info(TAG, "新增拉流代理", req.body);
        proxyModel.insert(req.body).then((rows) => {
            let ret = Object.assign(constants.httpCode.OK );
            // 去修改deviceCache里的 cameras 数据
            const item = req.body;
            item.recording=false;
            deviceCache.cameras.push(item);
            res.send(ret);
        }).catch((err) => {
            logger.error(TAG, "新增拉流代理失败", err);
            let ret = Object.assign(constants.httpCode.UNKNOWN );
            res.send(ret);
        });
    },
    remove: async function (req, res) {
        if(!basectrl.hasLogin(req, res)){
            return;
        }
        proxyModel.remove(req.body.camera_id);
        let ret = Object.assign(constants.httpCode.OK );
        res.send(ret);
    },
    update: async function (req, res) {
        if(!basectrl.hasLogin(req, res)){
            return;
        }
        // 如果 channel_id 或 name已经存在
        let existChannelId = await proxyModel.exist('channel_id', req.body.channel_id, req.body.camera_id);
        if (existChannelId ) {
            logger.info(TAG, "更新时发现重复的channel_id或name");
            let ret = Object.assign(constants.httpCode.DUPLICATED);
            res.send(ret);
            return;
        }


        proxyModel.update(req.body).then(async (rows) => {
            let ret = Object.assign(constants.httpCode.OK );
            // 更新 deviceCache.cameras 缓存
            let camera;
            deviceCache.cameras.map((item) => {
                if(item.camera_id === req.body.camera_id){
                    item.name = req.body.name;
                    item.channel_id = req.body.channel_id;
                    item.mrl = req.body.mrl;
                    item.record = req.body.record;
                    item.in_use = req.body.in_use;
                    item.server_id = req.body.server_id;
                    camera=item;
                }
            });
            if(camera) {
                // 如果录制
                const isRecording = await zlMediaKit.isZlkRecording(camera);
                if (req.body.record) {
                    if (!isRecording) {
                        await zlMediaKit.startZlkRecord(camera);
                    }
                } else {
                    if (isRecording) {
                        await zlMediaKit.stopZlkRecord(camera);
                    }
                }
            }
            res.send(ret);
        }).catch((err) => {
            logger.error(TAG, "更新拉流代理失败", err);
            let ret = Object.assign(constants.httpCode.UNKNOWN );
            res.send(ret);
        });
    },
    list: async function (req, res) {
        if(!basectrl.hasLogin(req, res)){
            return;
        }
        const rows = deviceCache.cameras;
        logger.info("查询值", rows);
        // 每个添加生成的播放 url
        // 取第一个媒体服务器
        try {
            const mediaServers = await mediaServerModel.list(1, 10000)
            logger.info("媒体服务器", mediaServers);
            if(mediaServers.length===0){
                throw new Error("请首先设置媒体服务器");
            }else {
                for (let i = 0; i < rows.length; i++) {
                    // 这里以后要优化
                    const mediaServer = await mediaServerModel.getInfoById(rows[i].server_id);
                    logger.info(TAG, "调试", mediaServer);
                    modelChannel.generateUrl(mediaServer, rows[i], 'proxy')
                }
                let ret = Object.assign(constants.httpCode.OK, {data: {items: rows, total: rows.length}});
                res.send(ret);
            }
        }catch (e){
            let ret = Object.assign(constants.httpCode.MEDIASERVER_NOT_EXIST);
            res.send(ret);
        }
    },
    getLastChannelId(req, res){
        // 取camera_id的最大值+1
        proxyModel.maxCameraId().then((max) => {
            // 组合 prefix
            if(!max)max=0;
            const channelId = sipUtils.generateChannelId(max);
            let ret = Object.assign(constants.httpCode.OK, {data: channelId});
            res.send(ret);
        }).catch((err) => {
            logger.error('getLastChannelId', err);
            res.send({'code': 1, 'msg': '出现异常' + err});
        });
    }
}
module.exports = Proxy;
